<template>
  <q-select
    class="my-select-box"
    dense
    outlined
    options-dense
    clearable
    v-model="param.option"
    :options="options"
    option-value="label"
    emit-value
    @clear="clearData"
    @update:model-value="updateData"
  >
    <template v-slot:option="scope">
      <q-item v-bind="scope.itemProps">
        <q-item-section>
          <q-avatar rounded size="md">
            <img :src="scope.opt.label" alt="">
          </q-avatar>
        </q-item-section>
      </q-item>
    </template>
  </q-select>
</template>

<script lang="ts">
import { defineComponent, ref, toRefs, onMounted, watch, toRef } from 'vue';


export default defineComponent({
  name: 'ImgSelectBox',
  props: {
    options: {
      type: Array,   //传递对象数组
      default: () => {
        return []
      }
    },

    optionValue: {
      type: String,   //传递的是单个字符串
      default: () => {
        return ''
      }
    },

    width: {
      type: Number,
      default: () => {
        return 180
      }
    }
  },
  emits: ['update:optionValue'],
  setup (props, context) {
    //数据解构
    const {
      options,
      optionValue,
      width
    } = toRefs(props);

    //选择项，只用来显示label,设置q-select的option-value，emit-value
    let param = ref({
      option: ''
    });

    //定义图标
    const updateData = () => {
      if (param.value.option) {
        context.emit('update:optionValue', param.value.option);
      } else {
        context.emit('update:optionValue', '');
      }
    }

    //清楚图标
    const clearData = () => {
      param.value.option = '';
    }

    //*******************************
    //      启动模块
    //*******************************
    //初始化
    const init = () => {
      param.value.option = optionValue.value;
    }

    //监视数据源
    watch(optionValue, () => {
      init();
    }, { deep: true });

    //加载数据
    onMounted(() => {
      init();
    });

    return {
      options,
      width,
      param,
      updateData,
      clearData
    }
  }
})
</script>

<style lang="scss" scoped>
.my-select-box {
  max-width: 400px;
  overflow: hidden;  // 超出的文本隐藏
  text-overflow: ellipsis; // 溢出用省略号显示
}

</style>
